import 'package:flutter/material.dart';
import 'package:ichinesereader/controller/register.dart';
import 'package:ichinesereader/models/register/paymentRecordICR.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';

class PurchaseRecordsICRDataGrid extends StatefulWidget {
  //PurchaseRecordsDataGrid(this.purchaseRecordItems);
  @override
  State<PurchaseRecordsICRDataGrid> createState() =>
      _PurchaseRecordsICRDataGrid();
}

class _PurchaseRecordsICRDataGrid extends State<PurchaseRecordsICRDataGrid> {
  final RegisterController controller = Get.put(RegisterController());
  List<Transaction>? purchaseRecordICRItems = [];
  bool show = false;
  @override
  void initState() {
    //PaymentRecord? res = await controller.getPaymentRecordListICA();
    controller.getPaymentRecordICRList().then((value) => setState(() {
          purchaseRecordICRItems = value?.transactions;
          show = true;
        }));
    super.initState();
  }

  bool isWebOrDesktop =
      GetPlatform.isMacOS || GetPlatform.isWeb || GetPlatform.isDesktop;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();

  final box = Hive.box('appconfig');
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build payment history records grid DataGrids}');
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Account Transaction for IChineseReader'.tr,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            )),
        SizedBox(height: 20),
        show && purchaseRecordICRItems != null
            ? Row(
                children: [
                  Expanded(child: _buildDataGrid()),
                ],
              )
            : Text('notransactionIChineseICR'.tr),
      ],
    );
  }

  Container _buildDataGrid() {
    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source: PurchaseDataGridSource(items: purchaseRecordICRItems ?? []),
          isScrollbarAlwaysShown: true,
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          controller: _dataGridController,
          checkboxColumnSettings: Get.isDarkMode
              ? DataGridCheckboxColumnSettings(
                  backgroundColor: Color(0xff0a0e21),
                )
              : DataGridCheckboxColumnSettings(
                  backgroundColor: Colors.blue[50]),
          allowSorting: true,
          allowTriStateSorting: true,
          allowFiltering: true,
          selectionMode: SelectionMode.single,
          navigationMode: GridNavigationMode.row,
          endSwipeActionsBuilder:
              (BuildContext context, DataGridRow row, int rowIndex) {
            return GestureDetector(
                onTap: () {},
                child: Container(
                    color: Colors.redAccent,
                    child: Center(
                      child: Icon(Icons.delete),
                    )));
          },
          columns: <GridColumn>[
            GridColumn(
              columnName: 'Create Date'.tr,
              allowFiltering: false,
              width: 150,
              label: buildDataGridColumnLabel('Create Date'),
            ),
            GridColumn(
              columnName: 'Amount'.tr,
              allowFiltering: false,
              width: 130,
              label: buildDataGridColumnLabel('Amount'),
            ),
            GridColumn(
              columnName: 'Product'.tr,
              allowFiltering: false,
              width: 130,
              label: buildDataGridColumnLabel('Product'),
            ),
            GridColumn(
              columnName: 'Status'.tr,
              allowFiltering: false,
              width: 130,
              label: buildDataGridColumnLabel('Status'),
            ),
            // GridColumn(
            //   columnName: 'Expire Date'.tr,
            //   allowFiltering: false,
            //   width: 150,
            //   label: buildDataGridColumnLabel('Expire Date'),
            // ),
            GridColumn(
              columnName: 'Payment Mode',
              allowFiltering: false,
              width: 180,
              label: buildDataGridColumnLabel('Payment Mode'),
            ),
            GridColumn(
              columnName: 'Coupon'.tr,
              allowFiltering: false,
              width: 220,
              label: buildDataGridColumnLabel('Coupon'),
            ),
            // GridColumn(
            //   columnName: 'Invoice',
            //   label: Text('Invoice'),
            // ),
          ],
        ),
      ),
    );
  }
}

class PurchaseDataGridSource extends DataGridSource {
  PurchaseDataGridSource({required List<Transaction> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<int>(
                  columnName: 'Create Date', value: dataGridRow.createdAt),
              DataGridCell<String?>(
                  columnName: 'Amount', value: '\$ ${dataGridRow.amount}'),
              DataGridCell<String>(
                  columnName: 'Product', value: dataGridRow.planId),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.status?.toUpperCase()),
              // DataGridCell<int>(
              //     columnName: 'Expire Date',
              //     value: dataGridRow.details![0].expirationTime),

              DataGridCell<String>(
                  columnName: 'Payment Mode',
                  value: dataGridRow.creditCard?.maskedNumber),
              DataGridCell<String>(
                  columnName: 'Coupon', value: dataGridRow.discounts?[0].name),
              // no this kind of data
              // DataGridCell<String>(
              //     columnName: 'Invoice', value: dataGridRow.invoice),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];
  final box = Hive.box('appconfig');
  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Create Date' ||
              dataGridCell.columnName == 'Expire Date') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  DateFormat('MM/dd/yyyy').format(
                      DateTime.fromMillisecondsSinceEpoch(dataGridCell.value)),
                  style: Get.textTheme.bodySmall,
                ));
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
